package com.intelli.eve.core.impl.threads;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intelli.eve.core.impl.configuration.Configuration;
import com.intelli.ray.core.Inject;
import com.intelli.ray.core.ManagedComponent;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * Author: Sergey42
 * Date: 05.04.14 17:04
 */
@ManagedComponent(name = BackgroundTaskManager.NAME)
public class BackgroundTaskManager {

    public static final String NAME = "BackgroundTaskManager";

    @Inject
    protected Configuration configuration;

    protected ScheduledExecutorService scheduledExecutorService;
    protected ExecutorService executorService;

    @PostConstruct
    protected void init() {
        int fixedPoolSize = configuration.getIntProperty("backgroundTaskManager.fixedPoolSize", 10);
        int scheduledPoolSize = configuration.getIntProperty("backgroundTaskManager.scheduledPoolSize", 10);

        ThreadFactory esFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(NAME + "_ES-%d").build();
        ThreadFactory sesFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(NAME + "_SES-%d").build();

        executorService = Executors.newFixedThreadPool(fixedPoolSize, esFactory);
        scheduledExecutorService = Executors.newScheduledThreadPool(scheduledPoolSize, sesFactory);
    }

    public ScheduledFuture<?> scheduleTask(Runnable runnable, long delay, TimeUnit timeUnit) {
        return scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, delay, timeUnit);
    }

    public Future<?> submitTask(Runnable runnable) {
        return executorService.submit(runnable);
    }
}
